import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

const rightCode = 0 // 正确返回code
const logoutCode = 401 // 用户失效
const service = axios.create({
  // baseURL: '/', // VUE_APP_BASE_API = '/66/wisdom'
  // baseURL: '/', // VUE_APP_BASE_API = '/66/wisdom'
  //   baseURL: '/156/wisdom',
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000
})
let ifBusing

if (sessionStorage.getItem('ifBusing')) {
  ifBusing = sessionStorage.getItem('ifBusing')
} else {
  sessionStorage.setItem('ifBusing', false)
  ifBusing = false
}

// 请求拦截器
// 让每个请求都带上token
service.interceptors.request.use(config => {
  // console.log(config)
  // console.log(store)
  if (store.getters.token) {
    config.headers['Authorization'] = 'bearer' + ' ' + getToken() // token根据实际要求设置(后端传回token给前端)
  }
  return config
},
error => {
  console.log(error)
  return Promise.reject(error)
})

service.interceptors.re

// 响应拦截器
service.interceptors.response.use(response => {
  const res = response.data
  if (res.code && res.code !== rightCode) {
    if (res.code === logoutCode) {
      if (!ifBusing) {
        sessionStorage.setItem('ifBusing', true)
        ifBusing = true
        if (res?.msg && store?.getters?.hasToken) {
          console.log(store?.getters?.hasToken)
          MessageBox.confirm(res.msg + ',3秒后返回登录', '重新登录', {
            confirmButtonText: '重新登录',
            showCancelButton: false,
            showClose: false,
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              router.replace({
                path: '/'
              })
              // location.reload()
            })
          })
          setTimeout(() => {
            MessageBox.close()
            store.dispatch('user/resetToken').then(() => {
              router.replace({
                path: '/login'
              })
              // location.reload()
            })
          }, 3 * 1000)
        } else {
          store.dispatch('user/resetToken').then(() => {
            router.replace({
              path: '/login'
            })
            // location.reload()
          })
        }
      }
      return Promise.reject(new Error(res.msg || 'ERROR'))
    }
  } else {
    sessionStorage.setItem('ifBusing', false)
    ifBusing = false
  }
  return res
}, err => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误'
        break
      case 401:
        alert('已超时,请重新登陆!')
        localStorage.clear()
        location.href = '/'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = `请求地址出错: ${err.response.config.url}`
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器内部错误'
        break
      case 501:
        err.message = '服务未实现'
        break
      case 502:
        err.message = '网关错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持'
        break
      default:
    }
  }
  if (!ifBusing) {
    sessionStorage.setItem('ifBusing', true)
    ifBusing = true
    if (err.message.indexOf('Network Error') >= 0) {
      Message({
        type: 'error',
        message: '网络连接失败，请稍后再试',
        offset: 60,
        duration: 3 * 1000
      })
    } else if (err?.message) {
      Message({
        type: 'error',
        message: '网络连接失败，请稍后再试',
        offset: 60,
        duration: 3 * 1000
      })
    }
  }
  return Promise.reject(err)
})

export default service
